import 'package:flutter/foundation.dart';

/// API响应模型
/// 用于处理统一的响应格式
class ApiResponse<T> {
  final int code;
  final String message;
  final T? data;
  final String timestamp;

  ApiResponse({
    required this.code,
    required this.message,
    this.data,
    required this.timestamp,
  });

  factory ApiResponse.fromJson(
    Map<String, dynamic> json,
    T Function(dynamic)? fromJson,
  ) {
    debugPrint('ApiResponse - fromJson - 开始解析，输入: $json');

    try {
      // 处理错误响应
      if (json.containsKey('detail')) {
        debugPrint('ApiResponse - fromJson - 发现错误详情: ${json['detail']}');
        return ApiResponse(
          code: 404,
          message: json['detail'] as String,
          data: null,
          timestamp: DateTime.now().toIso8601String(),
        );
      }

      // 处理时间戳
      String timestamp;
      if (json.containsKey('timestamp')) {
        final rawTimestamp = json['timestamp'];
        timestamp =
            rawTimestamp is int
                ? DateTime.fromMillisecondsSinceEpoch(
                  rawTimestamp,
                ).toIso8601String()
                : rawTimestamp as String;
        debugPrint('ApiResponse - fromJson - 处理时间戳: $timestamp');
      } else {
        timestamp = DateTime.now().toIso8601String();
        debugPrint('ApiResponse - fromJson - 使用当前时间作为时间戳');
      }

      // 处理状态码
      final code = json['code'] as int? ?? 500;
      debugPrint('ApiResponse - fromJson - 状态码: $code');

      // 处理消息
      final message = json['message'] as String? ?? '未知错误';
      debugPrint('ApiResponse - fromJson - 消息: $message');

      // 处理数据
      T? data;
      if (json.containsKey('data') &&
          json['data'] != null &&
          fromJson != null) {
        try {
          debugPrint('ApiResponse - fromJson - 开始解析数据部分');
          data = fromJson(json['data']);
          debugPrint('ApiResponse - fromJson - 数据解析成功');
        } catch (e, stackTrace) {
          debugPrint('ApiResponse - fromJson - 数据解析错误: $e');
          debugPrint('错误堆栈: $stackTrace');
          rethrow;
        }
      } else {
        debugPrint(
          'ApiResponse - fromJson - 无数据需要解析: hasData=${json.containsKey('data')}, isNull=${json['data'] == null}, hasFromJson=${fromJson != null}',
        );
      }

      final result = ApiResponse(
        code: code,
        message: message,
        data: data,
        timestamp: timestamp,
      );

      debugPrint(
        'ApiResponse - fromJson - 解析完成: {code: $code, message: $message, hasData: ${data != null}}',
      );
      return result;
    } catch (e, stackTrace) {
      debugPrint('ApiResponse - fromJson - 解析过程发生错误: $e');
      debugPrint('错误堆栈: $stackTrace');
      rethrow;
    }
  }

  bool get isSuccess => code == 200;

  @override
  String toString() {
    return 'ApiResponse{code: $code, message: $message, data: $data, timestamp: $timestamp}';
  }
}

/// 分页数据模型
class PaginatedData<T> {
  final int total;
  final int page;
  final int pageSize;
  final List<T> items;

  PaginatedData({
    required this.total,
    required this.page,
    required this.pageSize,
    required this.items,
  });

  factory PaginatedData.fromJson(
    Map<String, dynamic> json,
    T Function(Map<String, dynamic>) fromJson,
  ) {
    final items =
        (json['items'] as List)
            .map((item) => fromJson(item as Map<String, dynamic>))
            .toList();

    return PaginatedData(
      total: json['total'] as int,
      page: json['page'] as int,
      pageSize: json['page_size'] as int,
      items: items,
    );
  }
}

/// 用户模型
class User {
  final int id;
  final String username;
  final String email;

  User({required this.id, required this.username, required this.email});

  factory User.fromJson(Map<String, dynamic> json) {
    return User(
      id: json['id'] is String ? int.parse(json['id']) : json['id'] as int,
      username: json['username'] as String,
      email: json['email'] as String,
    );
  }
}

/// 认证响应模型
class AuthResponse {
  final String accessToken;
  final String refreshToken;
  final String tokenType;
  final User user;

  AuthResponse({
    required this.accessToken,
    required this.refreshToken,
    required this.tokenType,
    required this.user,
  });

  factory AuthResponse.fromJson(Map<String, dynamic> json) {
    print('AuthResponse解析输入: $json'); // 添加调试日志
    final response = AuthResponse(
      accessToken: json['access_token'] as String,
      refreshToken: json['refresh_token'] as String,
      tokenType: json['token_type'] as String,
      user: User.fromJson(json['user'] as Map<String, dynamic>),
    );
    print('AuthResponse解析结果: ${response.user.id}'); // 添加调试日志
    return response;
  }
}

/// 文件上传响应模型
class FileUploadResponse {
  final int fileId;
  final String filename;
  final String originalFilename;
  final String storagePath;
  final int size;
  final String contentType;
  final String fileType;
  final String createTime;
  final String hash;
  final bool isDuplicate;

  FileUploadResponse({
    required this.fileId,
    required this.filename,
    required this.originalFilename,
    required this.storagePath,
    required this.size,
    required this.contentType,
    required this.fileType,
    required this.createTime,
    required this.hash,
    required this.isDuplicate,
  });

  factory FileUploadResponse.fromJson(Map<String, dynamic> json) {
    return FileUploadResponse(
      fileId: json['file_id'] as int,
      filename: json['filename'] as String,
      originalFilename: json['original_filename'] as String,
      storagePath: json['storage_path'] as String,
      size: json['size'] as int,
      contentType: json['content_type'] as String,
      fileType: json['file_type'] as String,
      createTime: json['create_time'] as String,
      hash: json['hash'] as String,
      isDuplicate: json['is_duplicate'] as bool,
    );
  }
}

/// 文件预览响应模型
class FilePreviewResponse {
  final String url;
  final String fileType;
  final String mimeType;
  final String fileName;
  final int fileSize;
  final String extension;
  final bool directPreview;

  FilePreviewResponse({
    required this.url,
    required this.fileType,
    required this.mimeType,
    required this.fileName,
    required this.fileSize,
    required this.extension,
    required this.directPreview,
  });

  factory FilePreviewResponse.fromJson(Map<String, dynamic> json) {
    return FilePreviewResponse(
      url: json['url'] as String,
      fileType: json['file_type'] as String,
      mimeType: json['mime_type'] as String,
      fileName: json['file_name'] as String,
      fileSize: json['file_size'] as int,
      extension: json['extension'] as String,
      directPreview: json['direct_preview'] as bool,
    );
  }
}

/// 文件下载响应模型
class FileDownloadResponse {
  final String url;
  final String fileName;
  final int fileSize;
  final String mimeType;

  FileDownloadResponse({
    required this.url,
    required this.fileName,
    required this.fileSize,
    required this.mimeType,
  });

  factory FileDownloadResponse.fromJson(Map<String, dynamic> json) {
    return FileDownloadResponse(
      url: json['url'] as String,
      fileName: json['file_name'] as String,
      fileSize: json['file_size'] as int,
      mimeType: json['mime_type'] as String,
    );
  }
}

/// 批量操作响应模型
class BatchOperationResponse {
  final int successCount;
  final int failedCount;
  final List<Map<String, dynamic>> failedFiles;
  final Map<String, dynamic>? data;

  BatchOperationResponse({
    required this.successCount,
    required this.failedCount,
    required this.failedFiles,
    this.data,
  });

  factory BatchOperationResponse.fromJson(Map<String, dynamic> json) {
    return BatchOperationResponse(
      successCount:
          json['success_count'] as int? ??
          json['total_success_count'] as int? ??
          0,
      failedCount:
          json['failed_count'] as int? ??
          json['total_failed_count'] as int? ??
          0,
      failedFiles:
          json['failed_files'] != null
              ? (json['failed_files'] as List)
                  .map((item) => item as Map<String, dynamic>)
                  .toList()
              : [],
      data: json,
    );
  }
}
